from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response

from areas.models import Area
from users.models import Address
from .serializers import AreasSerializers, AddressSerializers
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# Create your views here.
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView


class AreasView(ListAPIView, CacheResponseMixin):
    '''获取省的信息'''

    queryset = Area.objects.filter(parent=None)
    serializer_class = AreasSerializers


class AreaView(ListAPIView, CacheResponseMixin):
    '''获取市的信息'''

    serializer_class = AreasSerializers

    # 重写get_queryset, 指定返回数据内容
    def get_queryset(self):

        pk = self.kwargs['pk']

        return Area.objects.filter(parent_id=pk)


class AddressesView(CreateAPIView, ListAPIView, UpdateAPIView, DestroyAPIView):

    """保存用户收获地址"""
    serializer_class = AddressSerializers

    # 重写get_queryset,指定获取内容
    def get_queryset(self):

        return Address.objects.filter(user=self.request.user, is_deleted=False)

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(queryset, many=True)

        return Response({'addresses':serializer.data})

    def destroy(self, request, *args, **kwargs):

        instance = self.get_object()
        instance.is_deleted = True
        instance.save()

        return Response(status=status.HTTP_204_NO_CONTENT)